<template>
  <div class="menuSet">
    <div class="content__body">
      <el-form
        :model="formData"
        ref="formRef"
        :rules="formRules"
        label-width="80px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="资源路径" prop="resourceGroupKey">
              <el-input
                v-model="formData.resourceGroupKey"
                class="width-custom"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="页面名称" prop="resourceGroupName">
              <el-input
                v-model="formData.resourceGroupName"
                class="width-custom"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="资源描述" prop="resourceGroupDesc">
              <el-input
                v-model="formData.resourceGroupDesc"
                rows="3"
                type="textarea"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="是否项目菜单资源" prop="isProjectResource">
              <el-select
                clearable
                v-model="formData.isProjectResource"
                class="width-custom"
              >
                <el-option label="是" value="1" />
                <el-option label="否" value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formData.isProjectResource === '1'">
          <el-col :span="24">
            <el-form-item label="资源类型" prop="projectResourceType">
              <el-select
                clearable
                v-model="formData.projectResourceType"
                class="width-custom"
              >
                <el-option
                  v-for="item in resourceTypeList"
                  :key="item.dicCode"
                  :label="item.dicValue"
                  :value="item.dicCode"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="资源列表">
          <div class="content__body--table">
            <el-table
              :data="formData.resourceList"
              border
              width="80%"
              ref="tableRef"
            >
              <!-- <el-table-column type="index" label="序号" width="50">
              </el-table-column> -->
              <el-table-column label="资源名称">
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'resourceList.' + $index + '.resourceName'"
                    :rules="{
                      required: true,
                      message: '请填写完整',
                      trigger: 'change'
                    }"
                  >
                    <el-input
                      v-model="row.resourceName"
                      :disabled="mode === 'edit'"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="标识编号">
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'resourceList.' + $index + '.resourceKey'"
                  >
                    <!-- :rules="{
                      required: true,
                      message: '请填写完整',
                      trigger: 'change'
                    }" -->
                    <el-input
                      v-model="row.resourceKey"
                      :disabled="mode === 'edit'"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="接口标识">
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'resourceList.' + $index + '.interfaceKey'"
                  >
                    <!-- :rules="{
                      required: true,
                      message: '请填写完整',
                      trigger: 'change'
                    }" -->
                    <el-input
                      v-model="row.interfaceKey"
                      :disabled="mode === 'edit'"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="资源类型" width="180">
                <template #default="{ row }">
                  <el-form-item>
                    <el-select
                      :disabled="mode === 'edit'"
                      v-model="row.resourceType"
                      placeholder="Select"
                    >
                      <el-option
                        v-for="item in optionsType"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right" width="80">
                <template #default="{ $index }">
                  <el-button
                    :disabled="mode === 'edit'"
                    type="text"
                    @click="delResourceParams($index)"
                    style="margin-bottom: 18px"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <el-button
              v-if="mode === 'add'"
              class="table__footer--btn"
              size="mini"
              @click="addResourceParams"
              icon="el-icon-add"
              >添 加</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </div>

    <div class="content__footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSubmit">确 定</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  reactive,
  ref,
  toRefs,
  onMounted,
  nextTick,
  toRef
} from "vue";
// import { successMessage, warnMessage } from "/@/utils/message";
import NotifMessage from "/@/utils/message/notification";
import { cloneDeep } from "lodash-es";
import { postAddResource, postUpdateResource } from "/@/api/resource";
import { postDictList } from "/@/api/roles";
export default defineComponent({
  name: "menuSet",
  emits: ["emitClose", "updateClose"],
  props: {
    mode: {
      type: String,
      default: "add"
    },
    parentData: {
      type: Object
    }
  },
  setup(props, { emit }) {
    const tableRef = ref<HTMLTableElement | null>(null) as any;
    const formRef = ref<HTMLFormElement | null>(null) as any;
    let resourceTypeList = ref([]);
    let state = reactive({
      formData: {
        resourceGroupKey: "",
        resourceGroupName: "",
        resourceGroupDesc: "",
        isProjectResource: "",
        projectResourceType: "",
        resourceList: []
      }
    });

    const optionsType = [
      {
        value: "1",
        label: "URL"
      },
      {
        value: "2",
        label: "菜单"
      },
      {
        value: "3",
        label: "组件"
      },
      {
        value: "4",
        label: "接口"
      }
    ];

    const formRules = ref({
      resourceGroupKey: [
        { required: true, message: "请输入资源路径", trigger: "blur" }
      ],
      resourceGroupName: [
        { required: true, message: "请输入页面名称", trigger: "blur" }
      ],
      resourceGroupDesc: [
        { required: true, message: "请输入资源描述", trigger: "blur" }
      ],
      isProjectResource: [
        { required: true, message: "请选择是否项目菜单资源", trigger: "change" }
      ],
      projectResourceType: [
        { required: true, message: "请选择资源类型", trigger: "change" }
      ]
    });

    // 编辑
    if (props.mode === "edit") {
      const parentDataProp = toRef(props, "parentData");
      const copyparentDataProp = cloneDeep(parentDataProp.value);
      state.formData = copyparentDataProp;
    }

    // 添加新的按钮
    const addResourceParams = () => {
      state.formData.resourceList.push({
        resourceKey: "",
        resourceName: "",
        resourceType: "1",
        interfaceKey: ""
      });
    };
    // 删除当前操作类型
    const delResourceParams = index => {
      state.formData.resourceList.splice(index, 1);
    };

    // 提交表单信息
    const onAddResouceList = async () => {
      const isValid = await new Promise(resolve =>
        formRef.value.validate(resolve)
      );
      if (!isValid) return;
      try {
        const params = {
          ...state.formData
        };
        const { code, message } = await postAddResource(params);
        if (code === 200) {
          // successMessage(`${message}`);
          NotifMessage.success(message);
          emit("updateClose");
        } else {
          // warnMessage(`${message}`);
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 编辑表单信息
    const onEditResouceList = async () => {
      const isValid = await new Promise(resolve =>
        formRef.value.validate(resolve)
      );
      if (!isValid) return;
      try {
        const params = {
          ...state.formData
        };
        const { code, message } = await postUpdateResource(params);
        if (code === 200) {
          // successMessage(`${message}`);
          NotifMessage.success(message);
          emit("updateClose");
        } else {
          // warnMessage(`${message}`);
          NotifMessage.error(message);
        }
      } catch (err) {
        console.log(err);
      }
    };

    // 取消
    const handleCancel = () => {
      emit("emitClose");
    };
    // 确定
    const handleSubmit = () => {
      console.log(props.mode);
      if (props.mode === "add") {
        onAddResouceList();
      } else {
        onEditResouceList();
      }
    };

    //获取资源类型
    const initResourceTypeList = async () => {
      try {
        const { data } = await postDictList({ dicType: "thd_pro_res_type" });
        resourceTypeList.value = data || [];
      } catch (err) {
        console.log(err);
      }
    };

    // 表格显示错位，使用之前初始化
    onMounted(() => {
      nextTick(() => {
        if (tableRef.value) {
          tableRef.value.doLayout();
        }
      });
      initResourceTypeList();
    });

    return {
      ...toRefs(state),
      // IsDisplayEnum,
      // IsLeafEnum,
      optionsType,

      formRef,
      tableRef,
      formRules,
      // props,
      addResourceParams,
      delResourceParams,
      handleCancel,
      handleSubmit,
      resourceTypeList
    };
  }
});
</script>

<style lang="scss" scoped>
.menuSet {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;

  .content__body {
    width: 100%;
    flex: 1;
    padding: 15px;
    overflow-y: auto;
    overflow-x: hidden;
    &--table {
      padding: 0 15px 0 0;
      .table__footer--btn {
        margin-top: 10px;
        width: 100%;
        border: 1px dashed gray;
      }
    }
  }
  .content__footer {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 100%;
    height: 60px;
    border-top: 1px solid rgba(0, 21, 41, 0.15);
    padding: 15px;
  }
  :deep .el-select {
    width: 100%;
  }
  :deep .el-form-item__content {
    width: 95%;
  }
}
</style>
